﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Windows.Media.Imaging;
using CMCCMicroBlog.ViewModels;

namespace CMCCMicroBlog
{
    public partial class MainPage : PhoneApplicationPage
    {
        public const int HOMETIMELINE_INDEX=0;
        public const int ATME_INDEX=1;
        public const int COMMENT_INDEX=2;
        public const int PRIVATE_MSG_INDEX=3;

        //纬度与经度
        private double lat = 0;
        private double lon = 0;

        // 构造函数
        public MainPage()
        {
            InitializeComponent();

            // 将 listbox 控件的数据上下文设置为示例数据
            DataContext = App.ViewModel;
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        // 为 ViewModel 项加载数据
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!MainViewModel.IsHomeTimelineLoaded)
            {
                MainViewModel.LoadHomeTimeline(this,"","","");
            }
        }

        //设置
        private void settingsItem_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/SettinsPivotPage.xaml", UriKind.Relative));
        }

        //我的资料
        private void profileItem_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/ProfilePivotPage.xaml", UriKind.Relative));
        }

        //微博广场
        private void hallItem_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/HallPivotPage.xaml", UriKind.Relative));
        }

        //发布队列
        private void postQueueItem_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/PostQueuePivotPage.xaml", UriKind.Relative));
        }

        //日间模式
        private void dayModeItem_Click(object sender, EventArgs e)
        {

        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            //base.OnBackKeyPress(e);

            //如果处于发布界面,则关闭发布界面
            if (postCanvas.Visibility == Visibility.Visible)
            {
                ClosePostUI();
                e.Cancel = true;
                return;
            }

            //如果处于查看微博原始图片界面,则关闭查看界面
            if (originalPicCanvas.Visibility == Visibility.Visible)
            {
                closeOriginalImgButton_Click(null,null);
                e.Cancel = true;
                return;
            }

            //如果处于查看微博详情界面,则关闭微博详情界面
            if (feedCanvas.Visibility == Visibility.Visible)
            {
                feedCanvas.Visibility = Visibility.Collapsed;
                ApplicationBar = (Microsoft.Phone.Shell.ApplicationBar)Resources["homeTimelineBar"];
                e.Cancel = true;
                return;
            }

            MessageBoxResult result = MessageBox.Show("确定要退出移动微博？", "提示", MessageBoxButton.OKCancel);
            if (result == MessageBoxResult.OK)
            {
                Exit();
            }
            else
            {
                e.Cancel = true;
            }
        }

        private void ClosePostUI()
        {
            postCanvas.Visibility = Visibility.Collapsed;
            ApplicationBar = (Microsoft.Phone.Shell.ApplicationBar)Resources["homeTimelineBar"];
        }

        private void Exit()
        {
            while(NavigationService.BackStack.Any()){
                NavigationService.RemoveBackEntry();
            }

            this.IsHitTestVisible = this.IsEnabled = false;

            if (this.ApplicationBar != null)
            {
                foreach (var item in this.ApplicationBar.Buttons.OfType<ApplicationBarIconButton>())
                {
                    item.IsEnabled = false;
                }
            }
        }

        //点击刷新按钮
        private void refreshIconButton_Click(object sender, EventArgs e)
        {
            int selectedIndex=MainPivot.SelectedIndex;

            switch (selectedIndex)
            {
                case HOMETIMELINE_INDEX: refreshHomeTimeline(); break;
                case ATME_INDEX: refreshAtme(); break;
                case COMMENT_INDEX: refreshComment(); break;
                case PRIVATE_MSG_INDEX: refreshPrivateMsg(); break;
            }
        }

        private void refreshPrivateMsg()
        {
            MainViewModel.IsPrivateMsgLoaded = false;
            MainViewModel.LoadPrivateMsg(this, "", "", "");
        }

        private void refreshComment()
        {
            MainViewModel.IsCommentLoaded = false;
            MainViewModel.LoadComment(this, "", "", "");
        }

        private void refreshAtme()
        {
            MainViewModel.IsAtmeLoaded = false;
            MainViewModel.LoadAtme(this, "", "", "");
        }

        private void refreshHomeTimeline()
        {
            MainViewModel.IsHomeTimelineLoaded = false;
            MainViewModel.LoadHomeTimeline(this, "", "", "");
        }

        //点击显示分组
        private void groupIconButton_Click(object sender, EventArgs e)
        {

        }

        //点击发新微博
        private void addIconButton_Click(object sender, EventArgs e)
        {
            OpenPostUI();
        }

        private void OpenPostUI()
        {
            postCanvas.Visibility = Visibility.Visible;
            ApplicationBar = (Microsoft.Phone.Shell.ApplicationBar)Resources["postBar"];
        }

        //点击搜索
        private void searchIconButton_Click(object sender, EventArgs e)
        {

        }

        //关闭查看原始图片
        private void closeOriginalImgButton_Click(object sender, RoutedEventArgs e)
        {
            originalPic.Visibility = Visibility.Collapsed;
            originalCoverPic.Visibility = Visibility.Visible;

            originalPicCanvas.Visibility = Visibility.Collapsed;
            ApplicationBar.IsVisible = true;
        }

        private void Image_Tap(object sender, GestureEventArgs e)
        {
            Image img = (Image)sender;
            originalPic.Source = new BitmapImage(new Uri(img.Tag.ToString(),UriKind.RelativeOrAbsolute));
            
            ApplicationBar.IsVisible = false;
            originalPicCanvas.Visibility = Visibility.Visible;
        }

        private void thumbnailImage_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {
            ((Image)sender).Source = new BitmapImage(new Uri("/Images/gif.png", UriKind.RelativeOrAbsolute));
            ((Image)sender).Tag = "/Images/gif.png";
        }

        private void addGeoItem_Click(object sender, EventArgs e)
        {

        }

        private void removeImgItem_Click(object sender, EventArgs e)
        {

        }

        //通过网络发布微博
        private void postIconButton_Click(object sender, EventArgs e)
        {
            string postText = postTextBox.Text;

            if (postText == "" || postText.Trim() == "")
            {
                MessageBox.Show("不能发布空微博!");
                return;
            }

            WebClient wc = new WebClient();
            wc.DownloadStringCompleted += (s,ev) =>
            {
                ClosePostUI();
            };
            string query=string.Format("op=Status.update&text={0}&lat={1}&long={2}",postText,lat,lon);
            wc.DownloadStringAsync(App.BuildQueryUri(query));
        }

        private void addPicIconButton_Click(object sender, EventArgs e)
        {

        }

        private void atIconButton_Click(object sender, EventArgs e)
        {

        }

        private void emoIconButton_Click(object sender, EventArgs e)
        {

        }

        private void MainPivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int selectedIndex=((Pivot)sender).SelectedIndex;

            switch (selectedIndex)
            {
                case HOMETIMELINE_INDEX: ApplicationBar = (Microsoft.Phone.Shell.ApplicationBar)Resources["homeTimelineBar"]; break;
                case ATME_INDEX: initAtme(); ; break;
                case COMMENT_INDEX: initComment();  break;
                case PRIVATE_MSG_INDEX: initPrivateMsg();  break;
                default: ApplicationBar = (Microsoft.Phone.Shell.ApplicationBar)Resources["homeTimelineBar"]; break;
            }
        }

        private void initPrivateMsg()
        {
            if (!MainViewModel.IsPrivateMsgLoaded)
            {
                MainViewModel.LoadPrivateMsg(this, "", "", "");
            }
            ApplicationBar = (Microsoft.Phone.Shell.ApplicationBar)Resources["privateMsgBar"];
        }

        private void initComment()
        {
            if (!MainViewModel.IsCommentLoaded)
            {
                MainViewModel.LoadComment(this, "", "", "");
            }
            ApplicationBar = (Microsoft.Phone.Shell.ApplicationBar)Resources["commentBar"];
        }

        private void initAtme()
        {
            if (!MainViewModel.IsAtmeLoaded)
            {
                MainViewModel.LoadAtme(this, "", "", "");
            }
            ApplicationBar = (Microsoft.Phone.Shell.ApplicationBar)Resources["atmeBar"];
        }

        private void privateMsgIconButton_Click(object sender, EventArgs e)
        {

        }

        private void originalPic_ImageOpened(object sender, RoutedEventArgs e)
        {
            originalCoverPic.Visibility = Visibility.Collapsed;
            originalPic.Visibility = Visibility.Visible;
        }

        private void FeedPivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int selectedIndex = ((Pivot)sender).SelectedIndex;
            if (selectedIndex == 1)
            {

            }
        }

        private void repostIconButton_Click(object sender, EventArgs e)
        {

        }

        private void commentFeedIconButton_Click(object sender, EventArgs e)
        {

        }

        private void addFavIconButton_Click(object sender, EventArgs e)
        {

        }

        private void shareFeedItem_Click(object sender, EventArgs e)
        {

        }

        private void feedGrid_Tap(object sender, GestureEventArgs e)
        {
            FeedModel f = (FeedModel)((TextBlock)sender).Tag;

            MainViewModel.LoadFeed(this,f);

            feedCanvas.Visibility = Visibility.Visible;
            ApplicationBar = (Microsoft.Phone.Shell.ApplicationBar)Resources["feedBar"];

        }
    }
}